package com.weibo.common;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.weibo.menus.service.MenusService;
import com.weibo.menus.service.imp.MenusServiceImp;
import com.weibo.sql.CommonParm;
import com.weibo.user.User;

/**
 * Servlet implementation class ValidateUserServlet
 */
public abstract class ValidateUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(ValidateUserServlet.class);
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ValidateUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		if(validateUser(request,response)){
			initData(request,response);
			doService(request,response);
		}
	}
	/**
	 * 验证用户是否登陆 或者登陆超时
	 * @param request
	 * @param response
	 * @return
	 */
	public boolean validateUser(HttpServletRequest request, HttpServletResponse response){
		boolean flag = false;
		User user = CommonUtil.getLoginUser(request);
		if(user==null){
			try {
				request.setAttribute("login_info",CommonParm.LOGIN_TIMEOUT);
				request.getRequestDispatcher("/index.jsp").forward(request, response);
				//response.sendRedirect("/index.jsp");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error(e);
			}
		}else{
			request.setAttribute("login_user", user);
			flag = true;
		}
		return flag;
	}
	/**
	 * 初始化页面数据
	 * @param request
	 * @param response
	 */
	public void initData(HttpServletRequest request, HttpServletResponse response){
		//获取按钮列表
		MenusService menusService = new MenusServiceImp();
		List list_menu = menusService.getMenuList("");
		request.setAttribute("list_menu", list_menu);
	}
	/**
	 * 
	 * @param request
	 * @param response
	 */
	public abstract void doService(HttpServletRequest request, HttpServletResponse response);

}
